package thread.test4Queue.domain;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 用于delayQueue
 * see:  https://my.oschina.net/lujianing/blog/705894
 * Created by majian8 on 2018/11/12.
 */
public class PersonDelay implements Delayed{
    //延迟时间
    private long delay;
    //到期时间
    private long expire;
    private String name;

    public PersonDelay(long delay,String name) {
        this.delay = delay;
        //过期时间 就是当前时间加延迟时间
        this.expire = System.currentTimeMillis()+delay;
        this.name=name;
    }

    /**
     * 需要实现的接口，获得延迟时间   用过期时间-当前时间
     * 返回小于或等于0的元素时，发生到期
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire-System.currentTimeMillis(),TimeUnit.MICROSECONDS);
    }

    /**
     * 用于延迟队列内部比较排序   当前时间的延迟时间 - 比较对象的延迟时间
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        return (int)(this.getDelay(TimeUnit.MICROSECONDS)-o.getDelay(TimeUnit.MICROSECONDS));
    }





    public long getDelay() {
        return delay;
    }

    public void setDelay(long delay) {
        this.delay = delay;
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
